<?php
function check_XSS($text)
{
    $isXss = false;
    $list = array(
        '/onabort/is',
        '/onblur/is',
        '/onchange/is',
        '/onclick/is',
        '/ondblclick/is',
        '/onerror/is',
        '/onfocus/is',
        '/onkeydown/is',
        '/onkeypress/is',
        '/onkeyup/is',
        '/onload/is',
        '/onmousedown/is',
        '/onmousemove/is',
        '/onmouseout/is',
        '/onmouseover/is',
        '/onmouseup/is',
        '/onreset/is',
        '/onresize/is',
        '/onselect/is',
        '/onsubmit/is',
        '/onunload/is',
        '/eval/is',
        '/ascript:/is',
        '/style=/is',
        '/width=/is',
        '/width:/is',
        '/height=/is',
        '/height:/is',
        '/src=/is',  
    );
    if (strip_tags($text)) {
        for ($i = 0; $i < count($list); $i++) {
            if (preg_match($list[$i], $text) > 0) {
                $isXss = true;
                break;
            }
        }
    } else {
        $isXss = true;
    };
    return $isXss;
}

function reply($text,$word = true)
{
    if (check_XSS($text)) {
        $text = "该回复疑似异常，已被系统拦截！";
    }
    if($word == true){
        $text = strip_tags($text, "<img>");
    }else{
        $text = rtrim(strip_tags($text), "\n");
    }
    return $text;
}
function _article_changetext($post) {
    $content = $post->content;
    $cid = $post->cid;
    
    // 多媒体内容处理
    $content = preg_replace_callback(
    '/{(netease-music|bd-video|local-video|qq-music)}([\s\S]*?){\/\1}/',
        function($matches) {
            $type = $matches[1];
            $content = $matches[2];
            
            switch ($type) {
                case 'netease-music':
                    return '<media-embed class="netease-music">
                        <div style="margin: -10px;">
                            <iframe 
                                data-src="https://music.163.com/outchain/player?type=2&id='.$content.'&height=66" 
                                frameborder="no"
                                allowfullscreen>
                            </iframe>
                        </div>
                        <i class="loading">音乐加载中...</i>
                    </media-embed>';
                    
                case 'bd-video':
                    return '<media-embed class="iframe-video" data-type="bd">
                        <iframe 
                            data-src="https://www.bilibili.com/blackboard/html5mobileplayer.html?bvid='.$content.'&amp;as_wide=1&amp;danmaku=0&amp;hasMuteButton=1" 
                            scrolling="no" 
                            referrerpolicy="unsafe-url" 
                            allow="autoplay; encrypted-media" 
                            allowtransparency="true" 
                            allowfullscreen="true">
                        </iframe>
                        <i class="loading">视频加载中...</i>
                    </media-embed>';
                    
                case 'local-video':
                    $videoPath = htmlspecialchars(trim($content), ENT_QUOTES);
                    return '<media-embed class="iframe-video" data-type="local-video">
                        <video width="100%" controls><source src="'.$videoPath.'" type="video/mp4"></video>
                    </media-embed>';
                    
                case 'qq-music':
                    return '<media-embed class="qq-music">
                            <iframe 
                                data-src="https://i.y.qq.com/n2/m/outchain/player/index.html?songid='.$content.'" 
                                frameborder="no"
                                allowfullscreen>
                            </iframe>
                        <i class="loading">QQ音乐加载中...</i>
                    </media-embed>';
                    
                default:
                    return $matches[0];
            }
        },
        $content
    );
    
    // 图片懒加载处理
    $content = preg_replace(
        '/<img src([\s\S]*?)title="([\s\S]*?)">/', 
        '<div class="text-layout-img"><span data-caption="$2">'.
        '<img data-src$1 alt="$2"><div class="dynamic-background"></div><b>$2</b></span></div>', 
        $content
    );
    
    // 文章图片集处理
    /**
     * 处理内容中的 {photo-grid} 自定义标签并优化 HTML 结构
     * 1. 将 {photo-grid} 转换为 <div class="photo-grid">
     * 2. 移除包裹图片的冗余 <p> 标签
     * 3. 清理图片容器内的 <br> 标签
     */
    $content = preg_replace_callback(
        // 匹配 {photo-grid} 自定义标签
        '/\{photo-grid\}(.*?)\{\/photo-grid\}/s',
        function($matches) {
            // 获取标签内容并去除首尾空白
            $imageContent = trim($matches[1]);
            
            // 清理内容中的 <br> 标签（提前处理，避免后续重复处理）
            $imageContent = preg_replace('/<br\s*\/?>/i', '', $imageContent);
            
            // 返回包装后的 HTML 结构
            return '<div class="photo-grid">' . $imageContent . '</div>';
        },
        $content
    );
    
    // 处理可能被编辑器自动包裹的 <p> 标签
    $content = preg_replace_callback(
        // 匹配被 <p> 包裹的 photo-grid div（可能包含多余的 <br>）
        '/<p[^>]*>\s*(?:<br\s*\/?>)*\s*(<div class="photo-grid">[\s\S]*?<\/div>)\s*(?:<br\s*\/?>)*\s*<\/p>/i',
        function($matches) {
            // 直接返回纯净的 div 内容（内部 <br> 已在第一步处理）
            return $matches[1];
        },
        $content
    );
    
    // 文章表格功能处理
    $content = preg_replace(
        '/(<table\b[^>]*>[\s\S]*?<\/table>|^\|[\s\S]*?\|[^\n]*\n\|[\s\S]*?\|[^\n]*(\n\|[\s\S]*?\|[^\n]*)*)/m',
        '<div class="table-wrapper">$1</div>',
        $content
    );
    
    // 移除不必要的p标签包裹
    $content = preg_replace('/<p>\s*<\/p>/', '', $content);
    $content = preg_replace('/<p>\s*(<media-embed[\s\S]*?<\/media-embed>)\s*<\/p>/', '$1', $content);
    $content = preg_replace('/<p>\s*(<div class="text-layout-img">[\s\S]*?<\/div>)\s*<\/p>/', '$1', $content);
    
    echo $content;
}
//提取图片相关数据
function extract_img($img) {
    preg_match_all('/(id|alt|title|src)=("[^"]*")/i', $img, $matches);
    $ret = array();
    foreach($matches[1] as $i => $v) {
        $ret[$v] = $matches[2][$i];
    } 
    echo $ret;
}
function getArticleImage($obj, $place) {
    $content = $obj->content;
    $pattern = '/<\s*img[\s\S]+?(?:src=[\'"]([\S\s]*?)[\'"]\s*|alt=[\'"]([\S\s]*?)[\'"]\s*|[a-z]+=[\'"][\S\s]*?[\'"]\s*)+[\s\S]*?>/i';
    $replacement = '<img data-src="${1}" alt="${2}"><div class="dynamic-background"></div>';
    $content = preg_replace($pattern, $replacement, $content);
    
    preg_match_all('/<img[^>]+>/i', $content, $matches);
    $images = $matches[0];
 
    // 遍历所有图片并输出
    if (!empty($images)) {
        if ($place == 'nosingle') {
            $i = 1;
            foreach ($images as $image) {
                if ($i <= 3) {
                    // 确保包含 dynamic-background
                    $image_with_bg = preg_replace('/<img([^>]+)>/', '<img$1><div class="dynamic-background"></div>', $image);
                    echo '<li>'.$image_with_bg.'</li>';
                }
                $i++;
            }
        } elseif ($place == 'single') {
            foreach ($images as $image) {
                // 确保包含 dynamic-background
                $image_with_bg = preg_replace('/<img([^>]+)>/', '<img$1><div class="dynamic-background"></div>', $image);
                echo '<div class="post-content">'.$image_with_bg.'</div>';
            }  
        }
    }
}
/**
 * 解析一个视频链接
 * @param $content
 * @return mixed
 */
function parseFirstMusic($postObj) {
    // 先调用 _article_changetext 处理内容
    ob_start(); // 开启缓冲区捕获 echo 内容
    _article_changetext($postObj);
    $processedContent = ob_get_clean(); // 获取处理后的 HTML
    
    // 匹配音乐播放器
    $pattern = '/<media-embed\s+class="(netease-music|qq-music)">(.*?)<\/media-embed>/is';
    if (preg_match($pattern, $processedContent, $match)) {
        return $match[0];
    }
    return '';
}

function _getAbstract($item, $num) {
    $abstract = "";
    
    if ($item->password) {
        $abstract = "此文章已加密";
    } else {
        if ($item->fields->post_abstract) {
            $abstract = $item->fields->post_abstract;
        } else {
            $abstract = strip_tags($item->excerpt);
            $abstract = preg_replace('/\-o\-/', '', $abstract);
            $abstract = preg_replace('/{[^{]+}/', '', $abstract);
        }
    }
    
    if ($abstract === '') {
        $abstract = "此文章暂无简介";
    }
    
    return mb_substr($abstract, 0, $num);
}
Typecho_Plugin::factory('admin/write-post.php')->bottom = array('Editor', 'edit');
Typecho_Plugin::factory('admin/write-page.php')->bottom = array('Editor', 'edit');
class Editor
{
    public static function edit()
    {
        echo "<link rel='stylesheet' href='" . Helper::options()->themeUrl . '/assets/option.css' . "'>";
        echo "<script src='" . Helper::options()->themeUrl . '/assets/editor.js' . "'></script>";

    }
}